const con = require('./con.js'),
      log = console.log,
      fs  = require('fs'),
      https =  require('https'),
      sslify = require('koa-sslify').default,
      Koa = require('koa'),
      app = new Koa(),
      Router = require('koa-router'),
      router = new Router();
      
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

const options = {
  key:  fs.readFileSync('../fourgoldhua.cn.key'),
  cert: fs.readFileSync('../fourgoldhua.cn.crt')
}

//请求图片
async function getImg(share){
  const sql = `select * from img_table where id = '${share}'`;
  let [rows] = await con.execute(sql);
  return rows;
}
router.post('/getImg',async (ctx) => {
  let ac = ctx.request.body.share_id;
  let arr = await getImg(`${ac}`);
  ctx.body = arr;
})

//请求用户
async function getUser(share){
  const sql = `select id,user_name,user_img from user_table,main_table where user_id = id and share_id = '${share}'`;
  let [rows] = await con.execute(sql);
  return rows;
}
router.post('/getUser',async (ctx) => {
  let ac = ctx.request.body.share_id;
  let arr = await getUser(`${ac}`);
  ctx.body = arr;
})


//请求内容
async function getCt(share){
  const sql = `select * from main_table where share_id = '${share}'`;
  let [rows] = await con.execute(sql);
  return rows;
}
router.post('/getCt',async (ctx) => {
  let ac = ctx.request.body.share_id;
  let arr = await getCt(`${ac}`);
  ctx.body = arr;
})

//用户关注状态及其人数

async function getuser_dav_state(user_id,dav_id){
    const sql = `select state from concern_dav_table where user_id = '${user_id}' and dav_id ='${dav_id}'`;
    let [rows] = await con.execute(sql);
    return rows;
}

async function getdav_num(dav_id,state){
    const sql = `select * from concern_dav_table where dav_id ='${dav_id}' and state = '${state}'`;
    let [rows] = await con.execute(sql);
    return rows;
}
async function getshare_dav(share){
    const sql = `select * from main_table where share_id = '${share}'`;
    let [rows] = await con.execute(sql);
    return rows;
}
router.get('/getconcern',async (ctx) =>{
  let {user_id,share_id} =ctx.request.query;
  let brr = await getshare_dav(share_id);
  let dav_id = brr[0].user_id;
  let arr1 = await getuser_dav_state(user_id,dav_id);
  let state; 
  if(arr1.length==0) state = 2;
  else state = arr1[0].state;
  let a = await getdav_num(dav_id,1);
  let num = a.length;
  var arr=[];
  arr.push({
    "state":state,
    "num":num
  })
  log(arr);
  ctx.body = JSON.stringify(arr);
})

app.use(router.routes())
   .use(router.allowedMethods());

//app.listen(3005);
https.createServer(options,app.callback()).listen(3005);
